/**
 * @author SilverBiology, LLC
 * @website http://code.google.com/p/gbif-spreadsheet-processor/
*/
Ext.namespace('GBIF');
Ext.namespace('GBIF.GeoSpatial')

GBIF.GeoSpatial.CenterPanel = function(config){

	var tabs = [];

	this.mapComponent = new GBIF.GeoSpatial.MapComponent({
		region: 'center'
	});
	
	tabs.push(this.mapComponent);
	
	if (Config.GBIF.GeoSpatial.CenterPanel.showDataGridTabs) {
	
		this.tabmanager = new GBIF.GeoSpatial.TabManager({
				region: 'south'
			,	id: 'tabmanager'
			,	collapsible: true
			,	collapsedMode: 'mini'
			,	split: true
			,	height: Config.General.FeatureHeight
			,	tabConfig: {
						consoleShow: Config.GBIF.GeoSpatial.TabManager.tabConfig.consoleShow
					,	georssShow: Config.GBIF.GeoSpatial.TabManager.tabConfig.georssShow
					,	legendShow: Config.GBIF.GeoSpatial.TabManager.tabConfig.legendShow
					,	featuredatagrid: Config.GBIF.GeoSpatial.TabManager.tabConfig.featuredatagrid
				}
		});
				
		if (this.tabmanager.tabConfig.featuredatagrid) {
			this.featuredatagrid = this.tabmanager.featuredatagrid
			this.featuredatagrid.commit.on('click', this.senddata, this);
			this.featuredatagrid.on('rowClick', this.selectfeaturemap, this);
			this.featuredatagrid.on('deleteFeature', this.deletefeaturemap, this);
			this.featuredatagrid.on('centerToMap', this.moveMapToCenter, this);
			this.featuredatagrid.on('afterEdit', this.commitEditChanges, this);
		}
		tabs.push(this.tabmanager);
	}

	Ext.apply(this, config, {
			border:false
		,	items:tabs	
		,	layout:'border'
		,	controlConfig:{
					clickControl: Config.GBIF.GeoSpatial.CenterPanel.controlConfig.clickControl
				,	pointControl: Config.GBIF.GeoSpatial.CenterPanel.controlConfig.pointControl
				,	lineControl: Config.GBIF.GeoSpatial.CenterPanel.controlConfig.lineControl
				,	polygonControl: Config.GBIF.GeoSpatial.CenterPanel.controlConfig.polygonControl
				,	selectControl: Config.GBIF.GeoSpatial.CenterPanel.controlConfig.selectControl
				,	deleteControl: Config.GBIF.GeoSpatial.CenterPanel.controlConfig.deleteControl
				,	modifyControl: Config.GBIF.GeoSpatial.CenterPanel.controlConfig.modifyControl
			}
		,	listeners: {
				afterrender:function(){
						this.controlPanel();
					}
			}	
	});

	GBIF.GeoSpatial.CenterPanel.superclass.constructor.call(this,config);
}

Ext.extend(GBIF.GeoSpatial.CenterPanel, Ext.Panel, {
	
		callSaveFun:function(){
			this.scope.savetogrid();
		}

	,	commitEditChanges:function(grid){
			var vectors=false;
			Ext.each(this.mapComponent.map.layers, function(maplayer){
						if( maplayer.name == "Feature Layer")
								vectors = maplayer;		
			},this);
			var feature = vectors.getFeatureById(grid.record.data.id);
			feature.properties = {
							name: grid.record.data.name
						,	attribute: grid.record.data.attribute
				}
		}

	,	controlPanel:function(){
		    			
			/*
			*	
			*/
			var controlArray = [];
			var remove = true;
			var vectors = false;
			Ext.each(this.mapComponent.map.layers, function(maplayer){
				if( maplayer.name == "Feature Layer") {
					vectors = maplayer;		
				}
			}, this);
							
			if(!vectors){
				vectors = new OpenLayers.Layer.Vector(
						"Feature Layer"
					,	{
								allowOpacity: false
							,	allowDelete: false
							,	checked:true
						}
				);
			}
					
			var mouseControl = new OpenLayers.Control.MouseDefaults({
				title: 'Click on map and drag to pan.'
			});
			controlArray.push( mouseControl );
					
			if (this.controlConfig.deleteControl) {
				remove = false;
				var remove = new GBIF.GeoSpatial.RemoveFeature(
						vectors
					,	{	
								title: "Delete Feature"	
							,	onSelect: this.deleteFeature
							,	scope:this
							,	displayClass:'olControlRemoveFeature'
						}
				);
				controlArray.push(remove);	
			}
			
			if (this.controlConfig.modifyControl) {
				remove = false;
				var modify = new OpenLayers.Control.ModifyFeature(
						vectors
					,	{
								title: "Modify Feature"
							,	onModificationEnd:this.callSaveFun
							,	scope:this
						}
				);
				controlArray.push( modify );
			}
			
			if (this.controlConfig.selectControl) {
				remove = false;
				var SelectFeature= new OpenLayers.Control.SelectFeature(
						vectors
					,	{	
								title: "Select Feature"	
							,	onSelect:this.onselectfeature	
							,	deactivate:this.unselectFeature 
							,	scope:this
							,	displayClass:"olControlSelectFeature"
						}
				);
				controlArray.push(SelectFeature);				
			}
			
			if (this.controlConfig.polygonControl) {
				remove = false;
				var drawpolygon = new OpenLayers.Control.DrawFeature(
						vectors
					,	OpenLayers.Handler.Polygon
					,	{
								title: "Polygon Feature"
							,	clickout: true
							,	displayClass: 'olControldrawpolygon'
							,	scope: this
							,	multi: true
							,	featureAdded: this.callSaveFun
						}
				);
				controlArray.push(drawpolygon);	
			}
		
			if (this.controlConfig.lineControl) {
				remove = false;
				var drawline = new OpenLayers.Control.DrawFeature(
						vectors
					,	OpenLayers.Handler.Path
					,	{
								title: "Line Feature"
							,	clickout:true
							,	displayClass:'olControldrawline'
							,	featureAdded:this.callSaveFun
							,	scope:this
						}
				);
				controlArray.push(drawline);	
			}
			
			if (this.controlConfig.pointControl) {
				remove = false;
				var drawpoint= new OpenLayers.Control.DrawFeature(
						vectors
					,	OpenLayers.Handler.Point
					,	{
								title: "Point Feature"
							,	clickout:true	
							,	displayClass:'olControldrawpoint'
							,	featureAdded:this.callSaveFun
							,	scope:this
						}
				 );
				controlArray.push(drawpoint);	 
			}
		
			if (this.controlConfig.clickControl) {
				//remove = false;
				OpenLayers.Control.Click = OpenLayers.Class(OpenLayers.Control, {                
						defaultHandlerOptions: {
							single: true
						}
					,	initialize: function(options) {
							this.handlerOptions = OpenLayers.Util.extend(
								{}, this.defaultHandlerOptions
							);
							OpenLayers.Control.prototype.initialize.apply(this, arguments); 
							this.handler = new OpenLayers.Handler.Click(
								this, {
										'click': this.onClick
								}, this.handlerOptions
							);
						}
			
					,	onClick: function(evt) {
							var xy = evt.xy;
							Ext.each(this.map.layers,function(maplayer){
							if (maplayer.querable) {
								GBIF.GeoSpatial.BUS.fireEvent('sendRequest', maplayer,xy, this);
							}
						},this)
				}
			});
							
			var activeclick = new OpenLayers.Control.Click({
					title: "Inspect Layers"
				,	allowSelection:true
				,	displayClass: "olControlClickFeature"
				,	handlerOptions: {
						single: true
					}
				,	trigger: function() {
						Ext.each(panel.controls,function(control){
							if(control.title != 'Single Click' || control.title != 'Inspect Layers' ) {
								control.deactivate();
							}
						});

						if (singleclick.active) {
							activeclick.deactivate();
						} else {
							activeclick.activate();
						}
					}
			});
			controlArray.push(activeclick);
			
			if (!remove){
				this.mapComponent.map.addLayer(vectors);	
			} else {
				this.tabmanager.remove(this.featuredatagrid);
			}
				
				var panel = new OpenLayers.Control.Panel();
//	console.log("ca", controlArray);				
				panel.addControls(controlArray);
				panel.defaultControl = mouseControl;
			
				this.mapComponent.map.addControl(panel);		
				panel.activate();
				
			}
		}
	
	,	moveMapToCenter: function(lon,lat){
			this.mapComponent.map.setCenter(new OpenLayers.LonLat(lon || 0 , lat || 0));
		}
	
	,	unselectFeature: function(){
			this.unselectAll();
			if (this.active) {
				this.handlers.feature.deactivate();
				if(this.handlers.box) {
					this.handlers.box.deactivate();
				}
				if(this.layers) {
					this.map.removeLayer(this.layer);
				}
			}

			return OpenLayers.Control.prototype.deactivate.apply(this, arguments);
		}	
	
	,	selectfeaturemap:function(grid,index){
			var rec = grid.store.getAt(index);
			var veclayer;
				Ext.each(this.mapComponent.map.layers, function(maplayer){
						if( maplayer.name == "Feature Layer")
							veclayer = maplayer;		
				},this);
			var feature = veclayer.getFeatureById(rec.data.id);
			var selfeature = this.mapComponent.map.getControlsByClass('OpenLayers.Control.SelectFeature');
			selfeature[0].unselectAll();
			selfeature[0].select(feature);
		}
	
	,	onselectfeature:function(layer){
			this.tabmanager.setActiveTab(this.featuredatagrid);
			var index = this.featuredatagrid.store.findExact("id",layer.fid);
			this.featuredatagrid.getSelectionModel().selectRow(index);
		}
		
	,	savetogrid: function(){
			this.tabmanager.setActiveTab(this.featuredatagrid);
			var point = [];
			Ext.each(this.mapComponent.map.layers, function(maplayer){
				if( maplayer.name == "Feature Layer"){
					maplayer.setZIndex(10000);
					Ext.each(maplayer.features,function(feature){
						feature.fid = feature.id;	
						switch(feature.geometry.CLASS_NAME) {
							case "OpenLayers.Geometry.Point":
								var type = "Point"
								break;
							case "OpenLayers.Geometry.LineString":
								var type = "Line"
								break;
							case "OpenLayers.Geometry.Polygon":
								var type = "Polygon"
								break;
							}

							var data = {
									geometry: {
											type: type
										, coordinates: [feature.geometry.bounds.getCenterLonLat()]
									}
								,	state: feature.state
								, type: "Feature"
								, properties: {
											name: (typeof feature.properties == 'undefined')? "" : feature.properties.name
										,	attribute: (typeof feature.properties == 'undefined')? "" : feature.properties.attribute                   
									} 
								,	id: feature.id
							}
							point.push(data);

					}, this);
				}
			}, this);
			this.featuredatagrid.store.loadData(point);	
		}	
	
	,	senddata: function(){
			Ext.each( this.currentWFST.strategies, function( strategy ) {
				if (strategy.CLASS_NAME == "OpenLayers.Strategy.Save") {
					strategy.save();
				}
			});
/*		
			//var grid = this.featuredatagrid ;
			var params=[];//Ext.encode(grid.store.data.items);
			Ext.each(this.featuredatagrid.store.data.items,function(items){
				params.push(items.json);
			},this);
			Ext.Ajax.request({
					url: "../../resources/api/proxy.php"
				,	method: 'POST'
				,	scope:this
				,	params:Ext.encode(params)
				,	success: function(responseObject){
							//console.log('save',responseObject);	
					}
			}, this);
*/			
		}
	
	,	deletefeaturemap:function(){
			Ext.each(this.mapComponent.map.layers, function(maplayer){
				if( maplayer.name == "Feature Layer") {
					veclayer = maplayer;
				}
			},this);
			this.deleteFeature(veclayer.selectedFeatures);	
		}	

	,	deleteFeature:function(geometry){
			var veclayer;
			Ext.each(this.mapComponent.map.layers, function(maplayer){
				if( maplayer.name == "Feature Layer") {
					veclayer = maplayer;
				}
			},this);
			veclayer.removeFeatures(geometry);
			this.savetogrid(veclayer);
		}

});